package webTest.context.Util;

import webTest.context.PropClassLoad;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.List;

/**
 * Created by IFT8 on 2015/1/22.
 */
public class WebXMLOperate {
    public static String getServletURL(String servlet) {
        String path = PropClassLoad.class.getClassLoader().getResource("../../WEB-INF/web.xml").getPath();
        String servletURL = null;
        SAXReader saxReader = new SAXReader();
        Document document = null;
        try {
            document = saxReader.read(path);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        if (document != null) {
            // "//*[local-name()='servlet-mapping']" 选择所有servlet-mapping的节点
            List<Element> list = document.selectNodes("//*[local-name()='servlet-mapping']");
            if (list == null) {
                return servletURL;
            }
            for (Element element : list) {
                if (servlet.equals(element.element("servlet-name").getText())) {
                    servletURL = element.element("url-pattern").getText();
                }
            }
        }
        return servletURL;
    }
}
